package com.vichat.agent.init;


import com.vichat.common.cache.LocalCacher;
import com.vichat.common.constant.GlobalConstant;
import com.vichat.user.entity.SysStaticData;
import com.vichat.user.service.IStaticDataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;


/**
 * Created by wangluyin on 2017/8/23.
 */
@Component
public class ApplicationCacheInit implements ApplicationContextAware {

    private static transient Logger logger = LoggerFactory.getLogger(ApplicationCacheInit.class);

    private static ApplicationContext ctx;

    public ApplicationContext getApplicationContext() {

        return ctx;
    }

    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        try {
            this.ctx = ctx;
            LocalCacher.init(ctx);
            IStaticDataService staticDataService = (IStaticDataService) ctx.getBean("staticDataService", IStaticDataService.class);
            SysStaticData maxTerminalAuthNumber = staticDataService.getStaticData(GlobalConstant.SYSTEM_PARAM, "MAX_TERMINAL_AUTH_NUMBER");
            if (maxTerminalAuthNumber != null) {
                GlobalConstant.MAX_TERMINAL_AUTH_NUMBER = Long.parseLong(maxTerminalAuthNumber.getCodeName());
            }
            SysStaticData maxDispatcherAuthNumber = staticDataService.getStaticData(GlobalConstant.SYSTEM_PARAM, "MAX_DISPATCHER_AUTH_NUMBER");
            if (maxDispatcherAuthNumber != null) {
                GlobalConstant.MAX_DISPATCHER_AUTH_NUMBER = Long.parseLong(maxDispatcherAuthNumber.getCodeName());
            }
            SysStaticData checkDispatcherSn = staticDataService.getStaticData(GlobalConstant.SYSTEM_PARAM, "CHECK_DISPATCHER_SN");
            if (checkDispatcherSn != null) {
                GlobalConstant.CHECK_DISPATCHER_SN = Boolean.parseBoolean(checkDispatcherSn.getCodeName());
            }
            SysStaticData checkTerminalSn = staticDataService.getStaticData(GlobalConstant.SYSTEM_PARAM, "CHECK_TERMINAL_SN");
            if (checkTerminalSn != null) {
                GlobalConstant.CHECK_TERMINAL_SN = Boolean.parseBoolean(checkTerminalSn.getCodeName());
            }
            SysStaticData supportAdminLoginApp = staticDataService.getStaticData(GlobalConstant.SYSTEM_PARAM, "SUPPORT_ADMIN_LOGIN_APP");
            if (supportAdminLoginApp != null) {
                GlobalConstant.SUPPORT_ADMIN_LOGIN_APP = Boolean.parseBoolean(supportAdminLoginApp.getCodeName());
            }
        } catch (Exception e) {
            logger.error("ApplicationCache初始化失败", e);
        }
    }
}
